package com.aaa.ddd.controller;
import com.aaa.fpa.controller.BaseController;
import com.aaa.pojo.MyReturn;
import com.aaa.pojo.PageSort;
import com.aaa.pojo.Users;
import com.aaa.utils.Constants;
import com.aaa.utils.MyTools;
import com.aaa.ddd.service.DeptService;
import com.aaa.ddd.service.UserService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.github.pagehelper.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Resource
    private UserService userService;

    @Resource
    private DeptService deptService;

    MyReturn myReturn = new MyReturn();

    @RequestMapping("toShowUserPage.do")
    public ModelAndView toShowUserPage(ModelAndView modelAndView) {
        modelAndView.setViewName("showUser");
        return modelAndView;
    }

    @RequestMapping("/findAllUser.do")
    public MyReturn findAllUser(PageSort pageSort) {
        Page page = userService.findAllUser(pageSort);
        // System.out.println(page.getResult());
        myReturn.setData(page.getResult());
        myReturn.setCount(page.getTotal());
        return getSuccessResult(myReturn);
    }

    @RequestMapping("/queryAllDept.do")
    public MyReturn queryAllDept() {
        myReturn.setData(userService.queryAllDept());
        return myReturn;
    }

    /**
     * 查有没有重复名
     *
     * @param user 用户名
     * @return
     */
    @RequestMapping("/findNoSameName.do")
    public MyReturn findNoSameName(Users user) {
        boolean check = userService.findNoSameName(user);
        if (check) {
            getSuccessResult(myReturn);
            return myReturn;
        }
        getFailResult(myReturn);
        myReturn.setMsg(Constants.ROLE_NAME_EXIST);
        return myReturn;
    }

    @RequestMapping("/addUser.do")
    public MyReturn addUser(Users user, HttpSession httpSession) {
//        从session获取登录用户信息
       Users userInfo = (Users) httpSession.getAttribute("users");
//        把从session得到的用户信息添加到创建人
        user.setCreateBy(userInfo.getUsername() + "");
//        获取创建时间
        Timestamp createTime = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        user.setCreateTime(createTime);
//        用户默认头像
        user.setAvatar("https://av404.oss-cn-hangzhou.aliyuncs.com/av/1637995286971.jpg");
//        password加盐加密
        Map<String, String> salt = MyTools.makePasswordSalt(user.getPassword());
//        把密文和盐值添加到user中
        user.setPassword(salt.get("password"));
        user.setSalt(salt.get("salt"));
//        添加默认状态
        user.setStatus("1");
//        添加默认没有删除
        user.setDelFlag("1");
//        添加新用户
        boolean user1 = userService.addUser(user);
        if (user1) {
//            成功
            return getSuccessResult(myReturn);
        } else {
//            错误
            return getFailResult(myReturn);
        }
    }

    /**
     * 更新/重置密码
     *
     * @param user
     * @return
     */
    @RequestMapping("/resetPassword.do")
    public MyReturn resetPassword(Users user) {
//        加盐加密
        Map<String, String> salt = MyTools.makePasswordSalt(user.getPassword());
//        把密文和盐值添加到user中
        user.setPassword(salt.get("password"));
        user.setSalt(salt.get("salt"));
//        修改密码
        boolean password = userService.resetPassword(user);
//        操作成功/失败
        if (password) {
            return getSuccessResult(myReturn);
        } else {
            return getFailResult(myReturn);
        }
    }

    @RequestMapping("/updateUser.do")
    public MyReturn updateUser(Users userInfo, HttpSession httpSession) {
//        获取session中的登录信息
        Users attribute = (Users) httpSession.getAttribute("users");
//        获取修改人
        userInfo.setUpdateBy(attribute.getUsername() + "");
//        获取修改时间
        Timestamp updateTime = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        userInfo.setUpdateTime(updateTime);
//        修改状态
        if (userInfo.getStatus() != null && userInfo.getStatus() != "") {
            userInfo.setStatus("1");
        } else {
            userInfo.setStatus("0");
        }
//        执行修改
        boolean b = userService.updateUser(userInfo);
        if (b) {
            return getSuccessResult(myReturn);
        } else {
            return getFailResult(myReturn);
        }
    }

    /**
     * 通过用户id删除用户(单个/多个通用)(通过update修改del_flag为0把用户隐藏，不做真正的删除)
     * @param userid 用户id
     * @return
     */
    @RequestMapping("/deleteUser.do")
    public MyReturn deleteUser(String userid) {
//        获取前端传过来的用户id
        String useridStr = userid;
//        把获取到的字符串拆分为数组，分割条件是逗号
        String[] split = useridStr.split(",");
//        执行删除
        boolean b = userService.deleteUserById(split);
        if (b) {
            return getSuccessResult(myReturn);
        } else {
            return getFailResult(myReturn);
        }
    }
    @PostMapping("upload.do")
    @ResponseBody
    public MyReturn upload(MultipartFile xxx, HttpServletRequest request){
        //获取原始文件名
        String filename = xxx.getOriginalFilename();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tMaBaSR9SyPxD5cvy51";
        String accessKeySecret = "uUqwU6nnYajVZgZKYh12loN0Sf1krU";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "first00001";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = UUID.randomUUID()+filename;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String src = "https://" + bucketName + "." + endpoint + "/" + objectName;
        Map map = new HashMap();
        map.put("src",src);
        myReturn.setCode(0);
        myReturn.setData(map);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(xxx.getBytes()));
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return myReturn;
    }
    @RequestMapping("updateOneself.do")
    @ResponseBody
    public MyReturn updateOneself(Users userinfo){
        userinfo.setUpdateTime(Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())));
        userinfo.setUpdateBy(userinfo.getUsername());
        boolean state = userService.updateOneself(userinfo);
        if(state){
            return super.getSuccessResult(myReturn);
        }else{
            return super.getFailResult(myReturn);
        }
    }
}